package com.an.httptest;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

@SuppressWarnings("deprecation")
public class TestHttpGet {

	@SuppressWarnings("resource")
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		HttpGet httpGet = new HttpGet("https://www.baidu.com/?tn=sitehao123_15");
		String result = "";
		try {
			HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet);
			if(httpResponse.getStatusLine().getStatusCode() == 200) {
				HttpEntity httpEntity = httpResponse.getEntity();
				result = EntityUtils.toString(httpEntity);//取出应答字符串
				result.replaceAll("\r", "");//去掉返回结果中的"\r"字符，否则会在结果字符串后面显示一个小方格 
						
			}else {
				httpGet.abort();
			}
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			result = e.getMessage().toString();
		} catch (IOException e) {
			e.printStackTrace();
			result = e.getMessage().toString();
		}
		
		System.out.println(result);
		
		
		System.out.println("--------------");
		
		HttpPost httpPost = new HttpPost();
		try {
			httpPost.setURI(new URI("https://www.baidu.com"));
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("str", "hello beaidu"));
			
			httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
			
			HttpResponse httpResponse2 = new DefaultHttpClient().execute(httpPost);
			
			if(httpResponse2.getStatusLine().getStatusCode() == 200) {
				HttpEntity httpEntity2 = httpResponse2.getEntity();
				result = EntityUtils.toString(httpEntity2);
			}
			
		} catch (URISyntaxException e) {
			e.printStackTrace();
			result = e.getMessage().toString();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			result = e.getMessage().toString();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
			result = e.getMessage().toString();
		} catch (IOException e) {
			e.printStackTrace();
			result = e.getMessage().toString();
		}
		
		System.out.println("http post :" + result);
		
		
	}

}
